<script>
import api from '@/services/api'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

export default {
  name: 'SongDetailView',
  setup() {
    const route = useRoute()
    const store = useStore()
    const song = ref(null)
    const loading = ref(false)
    const error = ref('')
    const isPlaying = ref(false)
    const isFavorite = ref(false)
    const currentTime = ref(0)
    const duration = ref(0)
    const volume = ref(1)
    const audioPlayer = ref(null)

    const fetchSongDetails = async () => {
      loading.value = true
      error.value = ''
      try {
        const res = await api.get(`/music/${route.params.id}`)
        if (res.code === 0) {
          song.value = res.data
          isFavorite.value = res.data.isFavorite // 假设后端返回
        } else {
          error.value = res.message || '获取歌曲详情失败'
        }
      } catch (err) {
        error.value = '获取歌曲详情失败'
      } finally {
        loading.value = false
      }
    }

    //const togglePlay = () => {
    //  if (!audioPlayer.value) return
    //  if (isPlaying.value) {
    //    audioPlayer.value.pause()
    //  } else {
    //    audioPlayer.value.play()
    //  }
    //  isPlaying.value = !isPlaying.value
    //}

    const toggleFavorite = async () => {
      try {
        if (!song.value) return
        if (isFavorite.value) {
          await api.delete(`/music/${song.value.id}/favorite`)
        } else {
          await api.post(`/music/${song.value.id}/favorite`)
        }
        isFavorite.value = !isFavorite.value
        alert(isFavorite.value ? '已收藏' : '已取消收藏')
      } catch (err) {
        error.value = '操作失败，请重试'
      }
    }

    const addToPlaylist = async () => {
      // 这里需要弹窗选择歌单，示例直接用歌单ID 1
      try {
        await api.post(`/playlists/1/add-song/${song.value.id}`)
        alert('添加到歌单成功！')
      } catch (err) {
        error.value = '添加到歌单失败'
      }
    }

    const shareSong = () => {
      // TODO: 需要实现分享功能
      alert('分享功能待实现！')
    }

    const handleTimeUpdate = () => {
      if (audioPlayer.value) {
        currentTime.value = audioPlayer.value.currentTime
      }
    }

    const handleLoadedMetadata = () => {
      if (audioPlayer.value) {
        duration.value = audioPlayer.value.duration
      }
    }

    const handleVolumeChange = () => {
      if (audioPlayer.value) {
        audioPlayer.value.volume = volume.value
      }
    }

    const formatTime = (time) => {
      const minutes = Math.floor(time / 60)
      const seconds = Math.floor(time % 60)
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    }

    onMounted(() => {
      fetchSongDetails()
    })

    return {
      song,
      loading,
      error,
      isPlaying,
      isFavorite,
      currentTime,
      duration,
      volume,
      audioPlayer,
      //togglePlay,
      toggleFavorite,
      addToPlaylist,
      shareSong,
      handleTimeUpdate,
      handleLoadedMetadata,
      handleVolumeChange,
      formatTime,
    }
  },
}
</script>

<template>
  <div class="song-detail-container">
    <div v-if="error" class="error-message">{{ error }}</div>

    <div v-if="loading" class="loading-spinner">加载中...</div>

    <div v-else-if="song" class="song-content">
      <div class="song-header-section">
        <div class="song-cover-wrapper">
          <img :src="song.cover" :alt="song.title" class="song-cover" />
          <button class="play-toggle-btn" @click="togglePlay">
            <i :class="isPlaying ? 'fas fa-pause-circle' : 'fas fa-play-circle'"></i>
          </button>
        </div>
        <div class="song-info-main">
          <h1>{{ song.title }}</h1>
          <p class="artist-album">
            <span class="artist-name">{{ song.artist }}</span>
            <span class="separator">•</span>
            <span class="album-name">{{ song.album }}</span>
          </p>
          <p class="genre-duration">
            <span class="genre">流派：{{ song.genre }}</span>
            <span class="separator">•</span>
            <span class="duration">时长：{{ song.duration }}</span>
          </p>
          <p class="release-date">发行日期：{{ song.releaseDate }}</p>

          <div class="song-actions">
            <button class="action-button play-button" @click="togglePlay">
              <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
              {{ isPlaying ? '暂停' : '播放' }}
            </button>
            <button class="action-button favorite-button" :class="{ 'is-favorite': isFavorite }" @click="toggleFavorite">
              <i :class="isFavorite ? 'fas fa-heart' : 'far fa-heart'"></i>
              {{ isFavorite ? '已收藏' : '收藏' }}
            </button>
            <button class="action-button" @click="addToPlaylist">
              <i class="fas fa-plus"></i>
              添加到歌单
            </button>
            <button class="action-button" @click="shareSong">
              <i class="fas fa-share-alt"></i>
              分享
            </button>
          </div>
        </div>
      </div>

      <div class="player-controls-section">
        <audio
          ref="audioPlayer"
          :src="song.audioUrl"
          @timeupdate="handleTimeUpdate"
          @loadedmetadata="handleLoadedMetadata"
        ></audio>

        <div class="progress-bar-wrapper">
          <span class="time-display">{{ formatTime(currentTime) }}</span>
          <input
            type="range"
            :min="0"
            :max="duration"
            :value="currentTime"
            @input="(e) => (audioPlayer.currentTime = parseFloat(e.target.value))"
            class="progress-slider"
          />
          <span class="time-display">{{ formatTime(duration) }}</span>
        </div>

        <div class="volume-control-wrapper">
          <i class="fas fa-volume-up volume-icon"></i>
          <input
            type="range"
            min="0"
            max="1"
            step="0.05"
            v-model="volume"
            @input="handleVolumeChange"
            class="volume-slider"
          />
        </div>
      </div>

      <div class="info-sections">
        <div class="section-card">
          <h2>歌曲简介</h2>
          <p class="description-text">{{ song.description }}</p>
        </div>

        <div class="section-card">
          <h2>歌词</h2>
          <div class="lyrics-content">
            <p v-for="(line, index) in song.lyrics.split('\n')" :key="index" class="lyric-line">
              {{ line }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.song-detail-container {
  padding: 2rem;
  max-width: 1400px;
  margin: 0 auto;
  color: #fff;
}

.error-message,
.loading-spinner {
  text-align: center;
  padding: 3rem;
  font-size: 1.5em;
  color: #a0a0a0;
}

.song-content {
  background: #1c1c1c;
  border-radius: 20px;
  padding: 3rem;
  box-shadow: var(--box-shadow);
}

.song-header-section {
  display: flex;
  align-items: center;
  gap: 3rem;
  margin-bottom: 3rem;
  flex-wrap: wrap; /* 响应式布局 */
}

.song-cover-wrapper {
  position: relative;
  width: 250px;
  height: 250px;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
  flex-shrink: 0;
}

.song-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-toggle-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(69, 243, 255, 0.9);
  color: #1a1a1a;
  border: none;
  border-radius: 50%;
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 3em;
  cursor: pointer;
  opacity: 0;
  transition: all 0.3s ease;
}

.song-cover-wrapper:hover .play-toggle-btn {
  opacity: 1;
}

.song-info-main {
  flex-grow: 1;
}

.song-info-main h1 {
  font-size: 3.5em;
  margin-bottom: 0.5rem;
  color: #45f3ff;
}

.artist-album,
.genre-duration {
  font-size: 1.2em;
  color: #a0a0a0;
  margin-bottom: 0.8rem;
}

.artist-name,
.album-name {
  font-weight: bold;
  color: #fff;
}

.separator {
  margin: 0 10px;
  color: #666;
}

.release-date {
  font-size: 1em;
  color: #888;
  margin-bottom: 2rem;
}

.song-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.action-button {
  background-color: #333;
  color: white;
  border: 1px solid #555;
  border-radius: 30px;
  padding: 0.8rem 1.5rem;
  font-size: 1em;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.action-button:hover {
  background-color: #444;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.play-button {
  background-color: #45f3ff;
  color: #1a1a1a;
  border-color: #45f3ff;
  box-shadow: 0 5px 15px rgba(69, 243, 255, 0.4);
}

.play-button:hover {
  background-color: #fff;
  box-shadow: 0 8px 20px rgba(69, 243, 255, 0.6);
}

.favorite-button.is-favorite {
  color: #ff4580; /* Pink for favorite */
  border-color: #ff4580;
}

.favorite-button.is-favorite i {
  color: #ff4580;
}

.player-controls-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1.5rem;
  padding: 2rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  margin-bottom: 3rem;
  box-shadow: var(--box-shadow);
}

.progress-bar-wrapper {
  display: flex;
  align-items: center;
  gap: 1rem;
  width: 100%;
  max-width: 800px;
}

.time-display {
  font-size: 0.9em;
  color: #a0a0a0;
  min-width: 45px; /* Ensure consistent width */
  text-align: right;
}

.progress-slider {
  flex-grow: 1;
  -webkit-appearance: none;
  appearance: none;
  height: 8px;
  background: #555;
  border-radius: 5px;
  outline: none;
  cursor: pointer;
}

.progress-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #45f3ff;
  cursor: pointer;
  box-shadow: 0 0 5px rgba(69, 243, 255, 0.8);
}

.progress-slider::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #45f3ff;
  cursor: pointer;
  box-shadow: 0 0 5px rgba(69, 243, 255, 0.8);
}

.volume-control-wrapper {
  display: flex;
  align-items: center;
  gap: 1rem;
  width: 100%;
  max-width: 300px;
}

.volume-icon {
  font-size: 1.5em;
  color: #45f3ff;
}

.volume-slider {
  flex-grow: 1;
  -webkit-appearance: none;
  appearance: none;
  height: 6px;
  background: #555;
  border-radius: 5px;
  outline: none;
  cursor: pointer;
}

.volume-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #45f3ff;
  cursor: pointer;
  box-shadow: 0 0 5px rgba(69, 243, 255, 0.8);
}

.volume-slider::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #45f3ff;
  cursor: pointer;
  box-shadow: 0 0 5px rgba(69, 243, 255, 0.8);
}

.info-sections {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
}

.section-card {
  background: #282828;
  border-radius: 15px;
  padding: 2rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.section-card h2 {
  font-size: 2em;
  margin-bottom: 1.5rem;
  color: #45f3ff;
  border-bottom: 2px solid var(--primary-color);
  padding-bottom: 0.5rem;
  display: inline-block;
}

.description-text {
  font-size: 1.1em;
  line-height: 1.6;
  color: #e0e0e0;
}

.lyrics-content {
  font-family: 'monospace', 'Microsoft YaHei', sans-serif;
  font-size: 1.1em;
  line-height: 1.8;
  white-space: pre-wrap; /* 保持换行符 */
  color: #e0e0e0;
  max-height: 400px; /* 限制歌词高度 */
  overflow-y: auto;
  padding-right: 10px; /* 防止滚动条遮挡文字 */
}

.lyrics-content::-webkit-scrollbar {
  width: 8px;
}

.lyrics-content::-webkit-scrollbar-thumb {
  background-color: #45f3ff;
  border-radius: 4px;
}

.lyrics-content::-webkit-scrollbar-track {
  background-color: #333;
}

.lyric-line {
  margin-bottom: 0.5rem;
}

/* Responsive adjustments */
@media (max-width: 1024px) {
  .song-content {
    padding: 2rem;
  }

  .song-header-section {
    flex-direction: column;
    text-align: center;
    gap: 2rem;
  }

  .song-cover-wrapper {
    width: 200px;
    height: 200px;
  }

  .play-toggle-btn {
    width: 70px;
    height: 70px;
    font-size: 2.5em;
  }

  .song-info-main h1 {
    font-size: 3em;
  }

  .artist-album,
  .genre-duration {
    font-size: 1.1em;
  }

  .song-actions {
    justify-content: center;
  }

  .info-sections {
    grid-template-columns: 1fr;
  }

  .section-card {
    padding: 1.5rem;
  }
}

@media (max-width: 768px) {
  .song-detail-container {
    padding: 1rem;
  }

  .song-content {
    padding: 1.5rem;
  }

  .song-header-section {
    gap: 1.5rem;
  }

  .song-cover-wrapper {
    width: 180px;
    height: 180px;
  }

  .play-toggle-btn {
    width: 60px;
    height: 60px;
    font-size: 2em;
  }

  .song-info-main h1 {
    font-size: 2.5em;
  }

  .artist-album,
  .genre-duration {
    font-size: 1em;
  }

  .action-button {
    padding: 0.7rem 1.2rem;
    font-size: 0.9em;
  }

  .player-controls-section {
    padding: 1.5rem;
  }

  .time-display {
    font-size: 0.8em;
    min-width: 40px;
  }

  .volume-icon {
    font-size: 1.2em;
  }

  .section-card h2 {
    font-size: 1.8em;
  }

  .description-text,
  .lyrics-content {
    font-size: 1em;
  }
}
</style>
